/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.androidgap.plugin;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.ProgressDialog;

import com.phonegap.DroidGap;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class BusyIndicator extends Plugin {
	
	private ProgressDialog spinnerDialog = null;
	
	public void show(final String text) {
		if (this.spinnerDialog != null) {
			this.spinnerDialog.dismiss();
			this.spinnerDialog = null;
		}		
		final DroidGap ctx = (DroidGap) this.ctx;
		Runnable runnable = new Runnable() {
			public void run() {
				
				spinnerDialog = new ProgressDialog(ctx);
				spinnerDialog.setCancelable(true);
				spinnerDialog.setIndeterminate(true);
				spinnerDialog.setMessage(text);
				spinnerDialog.show();				
			};
		};
		this.ctx.runOnUiThread(runnable);
	}

	public void hide() {
		if (spinnerDialog != null ){
			spinnerDialog.dismiss();
			spinnerDialog = null;
		}
	}

	public boolean isVisible() {
		return spinnerDialog != null && spinnerDialog.isShowing();
	}

	@Override
	public PluginResult execute(String action, JSONArray args, String callbackId) {
		PluginResult.Status status = PluginResult.Status.OK;
		PluginResult result = new PluginResult(status, "");
		try {
			if (action.equals("show")){
				this.show(args.getString(0));
			}
			else if (action.equals("hide")){
				this.hide();
			}
			else if (action.equals("isVisible")){
				result = new PluginResult(status, this.isVisible());
			}
			return result;
		} 
		catch (JSONException e) {
			return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
		}
	}

	@Override
	public boolean isSynch(String action) {		
		return true;
	}	
}
